package com.jay.tools.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;


/**
 * Activity工具类
 *
 * @author
 */
public class ActivityUtils {

    private ActivityUtils() {

    }

    public static void jump(Context context, Class<?> cls) {
        jump(context, cls, -1, null);
    }

    public static void jump(Context context, Class<?> cls, int requestCode) {
        jump(context, cls, requestCode, null);
    }

    public static void jump(Context context, Class<?> cls, int requestCode, Bundle mBundle) {
        jump(context, cls, requestCode, mBundle, false);
    }

    /**
     * @param context     当前窗体
     * @param cls         目标窗体
     * @param requestCode 请求码
     * @param bundle      传递参数
     * @param clearTop    是否启动一个新实例的活动
     */
    public static void jump(Context context, Class<?> cls, int requestCode, Bundle bundle,
                            boolean clearTop) {
        Intent intent = new Intent(context, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }

        Activity activity = (Activity) context;

        if (clearTop) {
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        if (requestCode != -1) {
            intent.putExtra("requestCode", requestCode);
            activity.startActivityForResult(intent, requestCode);
        } else
            activity.startActivity(intent);
    }

    public static void replaceFragment(FragmentManager manager, int containerViewId, Fragment fragment) {
        FragmentTransaction tf = manager.beginTransaction();
        tf.replace(containerViewId, fragment);
        tf.commitAllowingStateLoss();
    }

    public static void replaceFragment(FragmentManager manager, Fragment fragment,
                                       int containerViewId, boolean addToBack, Bundle bundle) {
        FragmentTransaction tf = manager.beginTransaction();

        if (bundle != null) {
            fragment.setArguments(bundle);
        }
        if (addToBack) {
            tf.addToBackStack(fragment.getClass().getName());
        }
        tf.replace(containerViewId, fragment, fragment.getClass().getName());
        tf.commitAllowingStateLoss();
    }

    /**
     * 显示隐藏Fragment
     * @param manager
     * @param showFragment 显示Fragment
     * @param hideFragment 隐藏Fragment
     */
    public static void showFragment(FragmentManager manager, Fragment showFragment, Fragment hideFragment) {
        FragmentTransaction tf = manager.beginTransaction();
        tf.hide(hideFragment);
        tf.show(showFragment);
        tf.commitAllowingStateLoss();
    }
}
